import { useMutation } from "@tanstack/react-query";
import { logoutAPI } from "@/api";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { useErrorHandler } from "@/lib/error-handler";
import { useNavigate } from "react-router-dom";
import { useUserStore } from "@/stores";
import { Cookies } from "react-cookie";
import { TOKEN } from "@/constants/cookies";
import type { ErrorResponse, Response } from "@/types/response";
import type { AxiosError } from "axios";

/**
 * Logout hooks
 */
export const useLogout = () => {
  const { t } = useTranslation();
  const errorHandler = useErrorHandler();
  const navigate = useNavigate();
  const { clearUser } = useUserStore();
  const cookies = new Cookies();

  // Logout mutation
  const logoutMutation = useMutation({
    mutationFn: logoutAPI.logout,
    onSuccess: (response: Response) => {
      if (response.code === 200) {
        // 退出成功，清除本地状态
        clearUser();
        cookies.remove(TOKEN, { path: "/" });
        
        // 显示成功弹窗
        toast.success(t("Logout successful"), {
          description:
            response.message ||
            t("You have successfully logged out.", {
              defaultValue: "You have successfully logged out.",
            }),
          duration: 5000,
        });

        // 重定向到登录页面
        navigate("/cas/login");
      } else {
        // 退出失败，但仍然清除本地状态
        clearUser();
        cookies.remove(TOKEN, { path: "/" });
        
        toast.error(t("Logout failed"), {
          description:
            response.message ||
            t("An error occurred during logout. Please try again."),
          duration: 5000,
        });
        
        // 重定向到登录页面
        navigate("/cas/login");
      }
    },
    onError: (error: AxiosError<ErrorResponse, unknown>) => {
      // 即使API调用失败，也清除本地状态
      clearUser();
      cookies.remove(TOKEN, { path: "/" });
      
      // 使用错误处理器获取错误信息
      const errorResult = errorHandler.handleApiError(error);

      // 根据错误类型显示不同颜色的弹窗
      if (errorResult.type === "warning") {
        toast.warning(t("Logout failed"), {
          description: errorResult.message,
          duration: 5000,
        });
      } else {
        toast.error(t("Logout failed"), {
          description: errorResult.message,
          duration: 5000,
        });
      }
      
      // 重定向到登录页面
      navigate("/cas/login");
      console.error("Logout error:", error);
    },
  });

  return {
    logout: logoutMutation.mutate,
    logoutAsync: logoutMutation.mutateAsync,
    isLoggingOut: logoutMutation.isPending,
    logoutError: logoutMutation.error,
  };
};
